/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.analyzer.agent.behaviour;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Cancellable;

/**
 *
 * @author Tom
 */
public class UpdateTaskBarBehaviour extends CyclicBehaviour implements Cancellable {

	private static final Logger logger = Logger.getLogger(UpdateTaskBarBehaviour.class);
	private ProgressHandle taskBar = null;
	private AID receiver;

	public UpdateTaskBarBehaviour(AID receiver) {
		this.receiver = receiver;
	}

	@Override
	public void action() {
		if(this.taskBar == null) {
			ACLMessage reply = new ACLMessage(ACLMessage.SUBSCRIBE);
			reply.addReceiver(receiver);
			myAgent.send(reply);
		}
		ACLMessage msg = myAgent.blockingReceive(360000);
		if(msg != null) {
			if(this.taskBar == null) {
				this.taskBar = ProgressHandleFactory.createHandle(myAgent.getLocalName(), this);
				this.taskBar.start();
			}
			switch(msg.getPerformative()) {
				case ACLMessage.INFORM:
					String link = msg.getContent();
					this.taskBar.progress(link);
					logger.log(Level.DEBUG, "TaskBar updated with " + link);
					break;
				case ACLMessage.CANCEL:
					this.taskBar.finish();
					logger.log(Level.DEBUG, "TaskBar closing");
					myAgent.doDelete();
					break;
			}
		} else {
			if(taskBar != null) {
				this.taskBar.finish();
			}
			myAgent.doDelete();
		}
	}

	public boolean cancel() {
		ACLMessage msg = new ACLMessage(ACLMessage.CANCEL);
		msg.addReceiver(receiver);
		myAgent.send(msg);
		logger.log(Level.DEBUG, "Canceling agents for " + myAgent.getName());
		this.taskBar.finish();
		myAgent.doDelete();
		return true;
	}
}
